package com.example.jwtauthdemo.controller;


import com.example.jwtauthdemo.entity.ChangePasswordRequest;
import com.example.jwtauthdemo.model.User;

import com.example.jwtauthdemo.service.UserService;
import com.example.jwtauthdemo.util.JwtUtil;
import com.example.jwtauthdemo.util.MinioUtil;
import com.example.jwtauthdemo.util.Result;
import com.example.jwtauthdemo.util.ResultCode;
import com.example.jwtauthdemo.webclient.PersonalServiceClient;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/person")
public class PersonController {


    private static final Logger logger = LoggerFactory.getLogger(PersonController.class);
    
    private final PersonalServiceClient personalServiceClient;
    private final JwtUtil jwtUtil;
    private final ObjectMapper objectMapper;
    private final UserService userService;
    private final MinioUtil minioUtil;
    
    @Autowired
    public PersonController(PersonalServiceClient personalServiceClient, JwtUtil jwtUtil, ObjectMapper objectMapper, UserService userService, MinioUtil minioUtil) {
        this.personalServiceClient = personalServiceClient;
        this.jwtUtil = jwtUtil;
        this.objectMapper = objectMapper;
        this.userService = userService;
        this.minioUtil = minioUtil;
    }
    




    /**
     * 查询用户实名认证状态
     * @param authorization JWT令牌
     * @return 包含实名认证状态的Result对象
     */
    @GetMapping("/auth-status")
    public Result<Map<String, Object>> getAuthStatus(@RequestHeader("Authorization") String authorization) {
        logger.info("接收到查询用户实名认证状态的请求");
        
        try {
            // 验证Authorization头格式
            if (authorization == null || !authorization.startsWith("Bearer ")) {
                logger.warn("Authorization头格式不正确");
                return Result.error(ResultCode.UNAUTHORIZED, "Authorization头格式不正确");
            }
            
            // 提取JWT令牌
            String token = authorization.substring(7);
            
            // 从令牌中获取userId
            String userIdStr = jwtUtil.extractUserId(token);
            Long userId = null;
            try {
                userId = Long.parseLong(userIdStr);
            } catch (NumberFormatException e) {
                logger.warn("用户ID格式无效: {}", userIdStr);
                return Result.error(ResultCode.UNAUTHORIZED, "用户ID格式无效");
            }
            
            if (userId == null) {
                logger.warn("无法从令牌中获取用户ID");
                return Result.error(ResultCode.UNAUTHORIZED, "无法从令牌中获取用户ID");
            }

            
            logger.info("从令牌中提取到用户ID: {}", userId);
            
            // 调用Service层查询实名认证状态
            Map<String, Object> authStatus = userService.getRealNameAuthStatus(userId);
            
            logger.info("查询用户ID: {} 的实名认证状态成功", userId);
            return Result.success(authStatus);
            
        } catch (Exception e) {
            logger.error("查询用户实名认证状态失败: {}", e.getMessage(), e);
            return Result.error(ResultCode.INTERNAL_SERVER_ERROR, "查询用户实名认证状态失败: " + e.getMessage());
        }
    }
/**
     * 更新用户实名信息
     * @param file 用户上传的实名信息文件
     * @param authorizationHeader 请求头中的JWT令牌
     * @return 更新结果
     */

    
    @PostMapping("/updateRealName")

    public Result<Object> updateRealName(
            @RequestPart("file") MultipartFile file,
            @RequestHeader("Authorization") String authorizationHeader){
        try {
            //从token中获取userId
            if (authorizationHeader == null || !authorizationHeader.startsWith("Bearer ")) {
                logger.error("Authorization头缺失或格式错误");
                return Result.error(ResultCode.UNAUTHORIZED, "未提供有效的认证信息");
            }
            
            String jwt = authorizationHeader.substring(7); // 去掉"Bearer "前缀
            String userId = jwtUtil.extractUserId(jwt);
            
            logger.info("用户ID: {} 更新实名信息", userId);
            String responseJson = personalServiceClient.updateRealName(file, userId);
            
            // 解析JSON字符串并直接构建Result对象，避免嵌套的JSON结构
            try {
                // 首先将响应解析为Map以提取各个字段
                Map<String, Object> responseMap = objectMapper.readValue(responseJson, Map.class);
                
                // 提取code、message和data字段
                Integer code = (Integer) responseMap.get("code");
                String message = (String) responseMap.get("message");
                Object data = responseMap.get("data");
                
                // 创建新的Result对象，直接设置各个字段
                Result<Object> result = new Result<>();
                result.setCode(code != null ? code : ResultCode.SUCCESS.getCode());
                result.setMessage(message != null ? message : ResultCode.SUCCESS.getMessage());
                result.setData(data);
                return result;
            } catch (Exception e) {
                // 如果解析失败，记录日志并返回原始字符串包装的结果
                logger.warn("解析响应JSON失败: {}", e.getMessage());
                return Result.success(responseJson);
            }
        } catch (Exception e) {
            logger.error("更新实名信息失败: {}", e.getMessage());
            return Result.error(ResultCode.INTERNAL_SERVER_ERROR, "更新实名信息失败");
        }
    }
    
    /**
     * 用户更改密码
     * @param request 包含原密码和新密码的请求体
     * @param authorizationHeader 请求头中的JWT令牌
     * @return 更改结果
     */
    @PostMapping("/change-password")
    public ResponseEntity<Map<String, Object>> changePassword(
            @RequestBody ChangePasswordRequest request,
            @RequestHeader("Authorization") String authorizationHeader) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            // 提取JWT令牌
            String token = authorizationHeader.substring(7); // 去掉 "Bearer " 前缀
            String userIdStr = jwtUtil.extractUserId(token);
            Long userId = Long.parseLong(userIdStr);
            
            logger.info("接收到用户ID: {} 的密码更改请求", userId);
            
            // 验证请求参数
            if (request.getOldPassword() == null || request.getOldPassword().trim().isEmpty()) {
                response.put("status", "error");
                response.put("code", ResultCode.BAD_REQUEST.getCode());
                response.put("message", "原密码不能为空");
                return ResponseEntity.badRequest().body(response);
            }
            
            if (request.getNewPassword() == null || request.getNewPassword().trim().isEmpty()) {
                response.put("status", "error");
                response.put("code", ResultCode.BAD_REQUEST.getCode());
                response.put("message", "新密码不能为空");
                return ResponseEntity.badRequest().body(response);
            }
            
            // 调用Service层更改密码
            boolean success = userService.changePassword(userId, request.getOldPassword(), request.getNewPassword());
            
            if (success) {
                response.put("status", "success");
                response.put("code", ResultCode.SUCCESS.getCode());
                response.put("message", "密码更改成功");
                return ResponseEntity.ok(response);
            } else {
                response.put("status", "error");
                response.put("code", ResultCode.UNAUTHORIZED.getCode());
                response.put("message", "原密码不正确或新密码与原密码相同");
                return ResponseEntity.status(401).body(response);
            }
        } catch (NumberFormatException e) {
            logger.error("无效的用户ID格式: {}", e.getMessage());
            response.put("status", "error");
            response.put("code", ResultCode.BAD_REQUEST.getCode());
            response.put("message", "无效的用户ID");
            return ResponseEntity.badRequest().body(response);
        } catch (Exception e) {
            logger.error("更改密码时发生错误: {}", e.getMessage(), e);
            response.put("status", "error");
            response.put("code", ResultCode.INTERNAL_SERVER_ERROR.getCode());
            response.put("message", "服务器内部错误: " + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }
    
    /**
     * 获取用户真实姓名
     * @param authorization JWT令牌
     * @return 包含真实姓名的Result对象
     */
    @GetMapping("/real-name")
    public Result<Map<String, String>> getRealName(@RequestHeader("Authorization") String authorization) {
        logger.info("接收到获取用户真实姓名的请求");
        
        try {
            // 验证Authorization头格式
            if (authorization == null || !authorization.startsWith("Bearer ")) {
                logger.warn("Authorization头格式不正确");
                return Result.error(ResultCode.UNAUTHORIZED, "Authorization头格式不正确");
            }
            
            // 提取JWT令牌
            String token = authorization.substring(7);
            
            // 从令牌中获取userId
            String userIdStr = jwtUtil.extractUserId(token);
            Long userId = null;
            try {
                userId = Long.parseLong(userIdStr);
            } catch (NumberFormatException e) {
                logger.warn("用户ID格式无效: {}", userIdStr);
                return Result.error(ResultCode.UNAUTHORIZED, "用户ID格式无效");
            }
            
            if (userId == null) {
                logger.warn("无法从令牌中获取用户ID");
                return Result.error(ResultCode.UNAUTHORIZED, "无法从令牌中获取用户ID");
            }
            
            logger.info("从令牌中提取到用户ID: {}", userId);
            
            // 调用Service层获取真实姓名
            String realName = userService.getRealNameById(userId);
            
            Map<String, String> resultMap = new HashMap<>();
            resultMap.put("realName", realName != null ? realName : "");
            
            logger.info("获取用户ID: {} 的真实姓名成功", userId);
            return Result.success(resultMap);
            
        } catch (Exception e) {
            logger.error("获取用户真实姓名失败: {}", e.getMessage(), e);
            return Result.error(ResultCode.INTERNAL_SERVER_ERROR, "获取用户真实姓名失败: " + e.getMessage());
        }
    }


    /**
     *上传图片生成 url
     * @param file 图片文件
     * @param authorization JWT令牌
     * @return 包含图片URL的Result对象
     */
    @PostMapping("/uploadImage")
    public Result<Map<String, String>> uploadImage(
            @RequestPart("file") MultipartFile file,
            @RequestHeader("Authorization") String authorization) {
        logger.info("接收到图片上传请求");
        
        try {
            // 验证Authorization头格式
            if (authorization == null || !authorization.startsWith("Bearer ")) {
                logger.warn("Authorization头格式不正确");
                return Result.error(ResultCode.UNAUTHORIZED, "Authorization头格式不正确");
            }
            
            // 提取JWT令牌
            String token = authorization.substring(7);
            
            // 从令牌中获取userId
            String userIdStr = jwtUtil.extractUserId(token);
            Long userId = null;
            try {
                userId = Long.parseLong(userIdStr);
            } catch (NumberFormatException e) {
                logger.warn("用户ID格式无效: {}", userIdStr);
                return Result.error(ResultCode.UNAUTHORIZED, "用户ID格式无效");
            }
            
            if (userId == null) {
                logger.warn("无法从令牌中获取用户ID");
                return Result.error(ResultCode.UNAUTHORIZED, "无法从令牌中获取用户ID");
            }
            
            logger.info("用户ID: {} 上传图片", userId);
            
            // 调用MinioUtil上传图片
            String imageUrl = minioUtil.uploadImage(file);
            
            // 构建返回结果
            Map<String, String> resultMap = new HashMap<>();
            resultMap.put("url", imageUrl);
            
            logger.info("用户ID: {} 图片上传成功，URL: {}", userId, imageUrl);
            return Result.success(resultMap);
            
        } catch (IllegalArgumentException e) {
            logger.warn("图片上传参数错误: {}", e.getMessage());
            return Result.error(ResultCode.BUSINESS_ERROR, e.getMessage());
        } catch (RuntimeException e) {
            logger.error("图片上传失败: {}", e.getMessage(), e);
            return Result.error(ResultCode.BUSINESS_ERROR, e.getMessage());
        } catch (Exception e) {
            logger.error("图片上传时发生系统错误: {}", e.getMessage(), e);
            return Result.error(ResultCode.INTERNAL_SERVER_ERROR, "图片上传失败: " + e.getMessage());
        }
    }
    
    /**
     * 更新用户个人信息
     * @param user 包含要更新的用户信息的请求体
     * @param authorization JWT令牌
     * @return 更新结果
     */
    @PostMapping("/updateInformation")
    public Result<Map<String, Object>> updateInformation(
            @RequestBody User user, 
            @RequestHeader("Authorization") String authorization) {
        logger.info("接收到更新用户信息的请求");
        
        try {
            // 验证Authorization头格式
            if (authorization == null || !authorization.startsWith("Bearer ")) {
                logger.warn("Authorization头格式不正确");
                return Result.error(ResultCode.UNAUTHORIZED, "Authorization头格式不正确");
            }
            
            // 提取JWT令牌
            String token = authorization.substring(7);
            
            // 从令牌中获取userId
            String userIdStr = jwtUtil.extractUserId(token);
            Long userId = null;
            try {
                userId = Long.parseLong(userIdStr);
            } catch (NumberFormatException e) {
                logger.warn("用户ID格式无效: {}", userIdStr);
                return Result.error(ResultCode.UNAUTHORIZED, "用户ID格式无效");
            }
            
            if (userId == null) {
                logger.warn("无法从令牌中获取用户ID");
                return Result.error(ResultCode.UNAUTHORIZED, "无法从令牌中获取用户ID");
            }
            
            // 设置用户ID（确保只能更新自己的信息）
            user.setId(userId);
            
            logger.info("用户ID: {} 请求更新个人信息", userId);
            
            // 调用Service层更新用户信息
            boolean success = userService.updateUser(user);
            
            Map<String, Object> resultMap = new HashMap<>();
            if (success) {
                logger.info("用户ID: {} 个人信息更新成功", userId);
                resultMap.put("success", true);
                return Result.success(resultMap);
            } else {
                logger.warn("用户ID: {} 个人信息更新失败", userId);
                return Result.error(ResultCode.BUSINESS_ERROR, "个人信息更新失败");
            }
            
        } catch (RuntimeException e) {
            logger.error("更新用户信息时发生业务错误: {}", e.getMessage(), e);
            return Result.error(ResultCode.BUSINESS_ERROR, e.getMessage());
        } catch (Exception e) {
            logger.error("更新用户信息失败: {}", e.getMessage(), e);
            return Result.error(ResultCode.INTERNAL_SERVER_ERROR, "更新用户信息失败: " + e.getMessage());
        }
    }

}
